﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Company.Project.Application.Service.Interface;
using Company.Project.Infrastructure.Common;
using Company.Project.Domain.Base;
using Company.Project.Domain.Model;
using Company.Project.Domain.Model.DTO;
using Company.Project.Domain.Model.DTO.Manager;
using Company.Project.Infrastructure.Common.Enums;
using Company.Project.Web.Admin.Areas.Admin.Lib;
using Newtonsoft.Json;
using Company.Utility;
using Company.Utility.Extensions;
using Company.Project.Web.Areas.Admin.Attrbute;
using Company.Project.Web.Admin.Lib;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Npoi.Core.SS.Formula.Functions;

namespace Company.Project.Web.Areas.Admin.Controllers
{
    [FormHandle]
    public class SystemController : BaseController
    {
        private readonly IProject_Manager_BaseInfoServices _baseInfoServices;
        private readonly IProject_SYS_ModuleServices _moduleServices;
        private readonly IProject_SYS_ModuleActionServices _moduleActionServices;
        private readonly IProject_SYS_RoleServices _roleServices;
        private readonly IProject_SYS_WeChatSettingServices _weChatSettingServices;
        private readonly IProject_Manager_LogServices _logServices;
        private readonly IProject_SYS_ProvinceServices _provinceServices;
        private readonly IProject_SYS_CityServices _cityServices;
        private readonly IProject_SYS_DistrictServices _districtServices;
        private readonly ILocalCommon _localCommon;
        public SystemController(
            IProject_Manager_BaseInfoServices baseInfoServices,
            IProject_SYS_ModuleServices moduleServices,
            IProject_SYS_ModuleActionServices moduleActionServices,
            IProject_SYS_RoleServices roleServices,
            IProject_Manager_LogServices logServices,
            IProject_SYS_WeChatSettingServices weChatSettingServices,
            IProject_SYS_ProvinceServices provinceServices,
            IProject_SYS_CityServices cityServices,
            IProject_SYS_DistrictServices districtServices, ILocalCommon localCommon
            ):base(localCommon)
        {
            _baseInfoServices = baseInfoServices;
            _moduleServices = moduleServices;
            _moduleActionServices = moduleActionServices;
            _roleServices = roleServices;
            _logServices = logServices;
            _weChatSettingServices = weChatSettingServices;
            _provinceServices = provinceServices;
            _cityServices = cityServices;
            _districtServices = districtServices;
            _localCommon = localCommon;
        }
        #region 公共部分
        public async Task<IActionResult> GetFatherModule(Guid fatherId, Guid itemId)
        {
            return Json(await _moduleServices.GetFatherModule(fatherId, itemId));
        }
        public IActionResult GetEnumManagerState(Enum_ManagerUserState? code = null, bool isEmpty = false)
        {
            return Json(EnumHelper.EnumTypeGetListItem<Enum_ManagerUserState>(code?.GetValueToInt().ToString(), isEmpty));
        }
        public async Task<IActionResult> GetRoeLsit()
        {
            return Json(SelectListItemHelper.GetListByT((await _roleServices.GetManyAsync(new DirectSpecification<Project_SYS_Role>(x => !x.IsDeleted))).Select(x => new SelectListItem()
            {
                Text = x.RoleName,
                Value = x.ID.ToString()

            }), true));
        }
        
        public async Task<IActionResult> GetProvince(Guid? provinceId,bool isEmpty = true)
        {
            return Json(SelectListItemHelper.GetListByT((await _provinceServices.GetAllAsync()).Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.ProvinceName, Selected = provinceId != null && provinceId == x.ID }), isEmpty));
        }
        public async Task<IActionResult> GetCity(Guid? provinceId, Guid? cityId, bool isEmpty = true)
        {
            return Json(SelectListItemHelper.GetListByT((await _cityServices.GetManyAsync(new DirectSpecification<Project_SYS_City>(x => x.ProvinceId == provinceId))).Select(x => new SelectListItem{ Value= x.ID.ToString(),Text= x.CityName, Selected = cityId != null && cityId == x.ID }), isEmpty));
        }
        public async Task<IActionResult> GetDistrict(Guid? cityId, Guid? districtId, bool isEmpty = true)
        {
            return Json(SelectListItemHelper.GetListByT((await _districtServices.GetManyAsync(new DirectSpecification<Project_SYS_District>(x => x.CityId == cityId))).Select(x => new SelectListItem { Value = x.ID.ToString(), Text = x.DistrictName, Selected = districtId != null && districtId == x.ID }), isEmpty));
        }
        #endregion
        // GET: Admin/System
        #region 模块管理
        public async Task<IActionResult> Module(Guid? PId = null)
        {
            ViewBag.PId = PId ?? Guid.Empty;
            var opt = new JqGridOpt();
            if (PId == null)
            {
                opt.OptMainFun = "ModuleOpt";
                opt.OptWidth = 100;
            }
            else
            {
                var pid = (await _moduleServices.GetByKeyAsync(PId))?.PID;
                opt.OptMainFun = "ModuleOpt";
                opt.OptWidth = 100;
                ViewBag.Back = "/Admin/System/Module" + (pid == Guid.Empty ? "" : "?PID=" + pid);
            }
            ViewBag.ColumsTitle = GetColumsName<ModuleDTO>(opt);
            ViewBag.DataUrl = "/Admin/System/GetModuleList";

            return View();
        }
        public IActionResult AddModule()
        {
            return View("ModuleDetial", new Project_SYS_Module());
        }

        public async Task<IActionResult> EditModule(Guid Id)
        {
            var model = (await _moduleServices.GetByKeyAsync(Id));
            model.ModuleActions =
                (await _moduleActionServices.GetManyAsync(
                    new DirectSpecification<Project_SYS_ModuleAction>(x => !x.IsDeleted && x.ModuleID == Id))).ToList();
            return View("ModuleDetial", model);
        }

        [HttpPost]
        
        [SubAuth(nameof(AddModule), nameof(EditModule))]
        public async Task<IActionResult> SaveModule(Project_SYS_Module model)
        {
            var oldid = model.ID;
            TipResult result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                x.Success = true;
                await _moduleServices.AddModule(model);
                x.Message = "" + (oldid == Guid.Empty ? "添加" : "编辑") + "成功!";
            });
            return Json(result);
        }

        [SubAuth(nameof(Module))]
        public async Task<IActionResult> GetModuleList(int page, int rows, string sidx, string sord,Guid pid)
        {
            var sort = !string.IsNullOrEmpty(sidx) ? new Dictionary<string, string>() { { sidx, sord.ToUpper() } } : new Dictionary<string, string>() { { "OrderID", "ASC" } };
            return Json(GetRowToGrid((await _moduleServices.GetModuleList(page, rows, pid, sort))));
        }

        public async Task<IActionResult> DelModule(string ids)
        {
            TipResult result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                if (ids.Split(',').Any())
                {
                    var delId = ids.Split(',').Select(Guid.Parse);
                    await _moduleServices.DelModule(delId);
                    x.Success = true;
                    x.Message = "删除成功!";
                }
            });
            return Json(result);
        }
        #endregion
        #region 角色管理
        public IActionResult Role()
        {
            ViewBag.ColumsTitle = GetColumsName<RoleDTO>();
            ViewBag.DataUrl = "/Admin/System/GetRoleList";
            return View();
        }
        public async Task<IActionResult> AddRole()
        {
            await LoadModuleList(Guid.Empty);
            return View("RoleDetial", new Project_SYS_Role());
        }

        public async Task<IActionResult> EditRole(Guid Id)
        {
            await LoadModuleList(Id);
            return View("RoleDetial", (await _roleServices.GetByKeyAsync(Id)));
        }

        async Task LoadModuleList(Guid Id)
        {
            ViewBag.ModuleList =await _moduleServices.LoadModuleList(Id);
        }
        [HttpPost]
        [SubAuth(nameof(AddRole), nameof(EditRole))]
        
        public async Task<IActionResult> SaveRole(Project_SYS_Role model, List<Project_SYS_ModuleAction> moduleAction)
        {
            var oldid = model.ID;
            TipResult result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                x.Success = true;
                await _roleServices.AddRole(model, moduleAction);
                x.Message = "" + (oldid == Guid.Empty ? "添加" : "编辑") + "成功!"+ (oldid == Guid.Empty ? "" : "若涉及当前账户角色修改,请重新登录一次才能变更!") + "";
            });
            return Json(result);
        }
        [SubAuth(nameof(Role))]
        public async Task<IActionResult> GetRoleList(int page, int rows, string sidx, string sord)
        {
            var sort = !string.IsNullOrEmpty(sidx) ? new Dictionary<string, string>() { { sidx, sord.ToUpper() } } : new Dictionary<string, string>() { { "OrderID", "ASC" } };
            return Json(GetRowToGrid(await _roleServices.GetRoleList(page, rows, sort)));
        }
        public async Task<IActionResult> DelRole(string ids)
        {
            TipResult result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                if (ids.Split(',').Any())
                {
                    var delId = ids.Split(',').Select(Guid.Parse);
                    await _roleServices.DelRole(delId);
                    x.Success = true;
                    x.Message = "删除成功!";
                }
            });
            return Json(result);
        }
        #endregion
        #region 系统日志
        public IActionResult AdminLog()
        {
            ViewBag.ColumsTitle = GetColumsName<LogDTO>();
            ViewBag.DataUrl = "/Admin/System/GetAdminLogList";
            return View();
        }
        [SubAuth(nameof(AdminLog))]
        public async Task<IActionResult> GetAdminLogList(int page, int rows, string sidx, string sord, DateTime? searchStartCreateTime, DateTime? searchEndCreateTime, string searchText)
        {
            var sort = !string.IsNullOrEmpty(sidx) ? new Dictionary<string, string>() { { sidx, sord.ToUpper() } } : new Dictionary<string, string>() { { "CreateTime", "DESC" } };
            return Json(GetRowToGrid(await _logServices.GetLogList(page, rows, sort, searchStartCreateTime, searchEndCreateTime,searchText.UrlDecode())));
        }
        public async Task<IActionResult> DelAdminLog(string ids)
        {
            TipResult result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                if (ids.Split(',').Any())
                {
                    var delId = ids.Split(',').Select(Guid.Parse);
                    await _logServices.LogicDeleteAsync(new DirectSpecification<Project_Manager_Log>(y => delId.Contains(y.ID)));
                    x.Success = true;
                    x.Message = "删除成功!";

                }
            });
            return Json(result);
        }
        #endregion
        #region 系统用户管理
        public IActionResult Manager()
        {
            ViewBag.ColumsTitle = GetColumsName<BaseInfoDTO>();
            ViewBag.DataUrl = "/Admin/System/GetManagerList";
            return View();
        }
        public async Task<IActionResult> AddManager()
        {
            ViewBag.RoleList =await _roleServices.LoadMangerRoleList(Guid.Empty);
            return View("ManagerDetial", new Project_Manager_BaseInfo());
        }

        public async Task<IActionResult> EditManager(Guid Id)
        {
            ViewBag.RoleList =await _roleServices.LoadMangerRoleList(Id);
            return View("ManagerDetial",await _baseInfoServices.GetByKeyAsync(Id));
        }
        [HttpPost]
        
        [SubAuth(nameof(AddManager), nameof(EditManager))]
        public async Task<IActionResult> SaveManager(Project_Manager_BaseInfo model)
        {
            var oldid = model.ID;
            TipResult result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                var myid = CurrentUser.ID;
                await _baseInfoServices.AddMangerBaseInfo(model, myid);
                x.Success = true;
                x.Message = "" + (oldid == Guid.Empty ? "添加" : "编辑") + "成功!" +
                            (oldid == Guid.Empty ? "" : myid != model.ID ? "" : "您修改了自己的资料,重新登录后才能变更!");
            });
            return Json(result);
        }
        [SubAuth(nameof(Manager))]
        public async Task<IActionResult> GetManagerList(int page, int rows, string sidx, string sord, Enum_ManagerUserState? SeachState, Guid? Role, string sealogin)
        {
            sealogin = sealogin.UrlDecode();
            var sort = !string.IsNullOrEmpty(sidx) ? new Dictionary<string, string>() { { sidx, sord.ToUpper() } } : new Dictionary<string, string>() { { "CreateTime", "DESC" } };
            return Json(GetRowToGrid(await _baseInfoServices.GetManagerList(page, rows, sort, SeachState, Role, sealogin)));
        }
        public async Task<IActionResult> DelManager(string ids)
        {
            TipResult result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                if (ids.Split(',').Any())
                {
                    var delId = ids.Split(',').Select(Guid.Parse);
                   await _baseInfoServices.DelManager(delId,CurrentUser.ID);
                    x.Success = true;
                    x.Message = "删除成功!";
                }
            });
            return Json(result);
        }
        #endregion
        #region 微信设置
        public async Task<IActionResult> WeChatSetting()
        {
            return View("WeChatSettingDetial",(await _weChatSettingServices.GetAllAsync()).FirstOrDefault() ?? new Project_SYS_WeChatSetting());
        }

        [HttpPost]
        [SubAuth(nameof(WeChatSetting))]
        
        public async Task<IActionResult> SaveWeChatSetting(Project_SYS_WeChatSetting model)
        {
            var oldid = model.ID;
            TipResult result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                x.Success = true;
                await _weChatSettingServices.ModifyModel(model);
                x.Message = "" + (oldid == Guid.Empty ? "添加" : "编辑") + "成功!";
            });
            return Json(result);
        }
        #endregion
    }
}